﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.QPZS.EPC.API.Domain;
using Wicture.QPZS.EPC.API.Domain.Entities;
using Wicture.QPZS.EPC.API.InvokeContextBuilders.InvokeResultJudges;

namespace Wicture.QPZS.EPC.API.InvokeContextBuilders
{
    class ResultJudgeThrottedBuilder : IThrottedContextBuilder
    {
        public decimal Order => 2;

        private readonly IInvokeResultJudge[] _invokeResultJudges;
        private readonly IServiceHandlerSelector _serviceHandlerSelector;

        public ResultJudgeThrottedBuilder(IInvokeResultJudge[] invokeResultJudges, IServiceHandlerSelector serviceHandlerSelector)
        {
            _invokeResultJudges = invokeResultJudges;
            _serviceHandlerSelector = serviceHandlerSelector;
        }

        public void Build(ThrottlingContext context, object sender, ApiInvokedArgs e)
        {
            var judge = _serviceHandlerSelector.Select(_invokeResultJudges, context);
            if (judge == null)
            {
                context.IsSuccess = true;
                return;
            }
            context.IsSuccess = judge.Judge(e.Context.Result);
        }
    }
}
